<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use App\Models\StaffAuth;
use App\Models\OrderOutbound;
use App\Models\Order;
use App\Models\Member;
use App\Models\Store;
use App\Models\OrderOutboundGoods;
use App\Models\OrderGoods;
use App\Models\Goods;
use App\Models\VendorVerifiy;
use App\Models\PickupPointVendor;
use App\Models\HhmOrder;
use App\Models\HhmOrderGoods;
use App\Services\ImageUrlService;
use App\Models\CollectionCode;
use App\Services\CollectionCodeService;

class VerificationController extends Controller
{
    /**
     * 获取提货信息详情
     * POST /api/verification/detail
     * 
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function detail(Request $request)
    {
        try {
            // 获取参数
            $param = $request->input('param', []);
            $outboundId = $param['outbound_id'] ?? $request->input('outbound_id');
            $userId = $request->input('user_id');
            
            if (!$outboundId) {
                return response()->json([
                    'code' => 0,
                    'message' => '请提供发货单ID',
                    'data' => []
                ]);
            }

            // 权限验证：检查user_id是否提供
            if (!$userId) {
                return response()->json([
                    'code' => -1,
                    'message' => '未登录，请先登录',
                    'data' => [
                        'need_login' => true
                    ]
                ]);
            }

            // 查询发货单信息
            $outbound = OrderOutbound::where('id', $outboundId)->first();

            if (!$outbound) {
                return response()->json([
                    'code' => 0,
                    'message' => '发货单不存在',
                    'data' => []
                ]);
            }

            // 权限验证：检查用户是否有核销权限
            // 1. 获取发货单的供应商ID
            $vendorId = $outbound->vendor_id;
            
            // 2. 查询用户有权限的门店列表
            $authorizedStoreIds = StaffAuth::where('uid', $userId)
                ->where('status', StaffAuth::STATUS_AUTHORIZED)
                ->notDeleted()
                ->pluck('store_id')
                ->toArray();
            
            if (empty($authorizedStoreIds)) {
                return response()->json([
                    'code' => -2,
                    'message' => '您没有任何门店的核销权限',
                    'data' => [
                        'has_permission' => false
                    ]
                ]);
            }
            
            // 3. 查询这些门店中是否有关联该供应商的
            $matchedStore = PickupPointVendor::whereIn('store_id', $authorizedStoreIds)
                ->where('vendor_id', $vendorId)
                ->first();
            
            if (!$matchedStore) {
                return response()->json([
                    'code' => -2,
                    'message' => '您没有核销该供应商商品的权限',
                    'data' => [
                        'has_permission' => false
                    ]
                ]);
            }
            
            // 4. 获取匹配的门店信息
            $store = Store::where('id', $matchedStore->store_id)->first();
            
            if (!$store) {
                return response()->json([
                    'code' => 0,
                    'message' => '门店信息不存在',
                    'data' => []
                ]);
            }

            // 查询发货单商品信息
            $outboundGoods = OrderOutboundGoods::with(['orderGoods.goods'])
                ->where('outbound_id', $outboundId)
                ->get();

            // 查询订单信息
            $order = Order::where('id', $outbound->order_id)->first();

            if (!$order) {
                return response()->json([
                    'code' => 0,
                    'message' => '订单不存在',
                    'data' => []
                ]);
            }

            // 查询会员信息
            $member = Member::where('uid', $order->uid)->first();

            if (!$member) {
                return response()->json([
                    'code' => 0,
                    'message' => '会员信息不存在',
                    'data' => []
                ]);
            }

            // 组装商品列表数据
            $goodsList = [];
            foreach ($outboundGoods as $outboundGood) {
                $orderGoods = $outboundGood->orderGoods;
                $goods = $orderGoods ? $orderGoods->goods : null;
                
                if ($goods) {
                    $goodsList[] = [
                        'id' => $goods->id,
                        'name' => $goods->title,
                        'quantity' => $orderGoods->total,
                        'image' => ImageUrlService::processImageUrl($goods->thumb ?: '/static/images/default-product.png'),
                        'price' => $orderGoods->price
                    ];
                }
            }

            // 计算总数量
            $totalQuantity = array_sum(array_column($goodsList, 'quantity'));

            // 组装采购人信息
            $purchaserInfo = [
                'id' => $member->uid,
                'name' => $member->realname ?: $member->nickname ?: '未知用户',
                'avatar' => ImageUrlService::processImageUrl($member->avatar ?: '/static/images/default-avatar.png'),
                'mobile' => $member->mobile
            ];

            // 组装发货单基本信息
            $outboundInfo = [
                'id' => $outbound->id,
                'outbound_sn' => $outbound->outbound_sn,
                'order_sn' => $outbound->order_sn,
                'status' => $outbound->status,
                'status_text' => $this->getStatusText($outbound->status),
                'created_at' => $outbound->created_at,
                'send_time' => $outbound->send_time,
                'finish_time' => $outbound->finish_time,
                'vendor_id' => $outbound->vendor_id,
                'store_id' => $store ? $store->id : null
            ];

            return response()->json([
                'code' => 1,
                'message' => '查询成功',
                'data' => [
                    'outbound_info' => $outboundInfo,
                    'goods_list' => $goodsList,
                    'total_quantity' => $totalQuantity,
                    'purchaser_info' => $purchaserInfo,
                    'has_permission' => true
                ]
            ]);

        } catch (\Exception $e) {
            Log::error('查询提货信息失败', [
                'error' => $e->getMessage(),
                'trace' => $e->getTraceAsString(),
                'request_data' => $request->all()
            ]);

            return response()->json([
                'code' => 0,
                'message' => '查询失败: ' . $e->getMessage(),
                'data' => []
            ]);
        }
    }

    /**
     * 确认核销
     * POST /api/verification/confirm
     * 
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function confirm(Request $request)
    {
        try {
            // 获取参数
            $param = $request->input('param', []);
            $outboundId = $param['outbound_id'] ?? $request->input('outbound_id');
            
            if (!$outboundId) {
                return response()->json([
                    'code' => 0,
                    'message' => '请提供发货单ID',
                    'data' => []
                ]);
            }

            // 查询发货单是否存在
            $outbound = DB::table('ims_yz_order_outbound')
                ->where('id', $outboundId)
                ->first();

            if (!$outbound) {
                return response()->json([
                    'code' => 0,
                    'message' => '发货单不存在',
                    'data' => []
                ]);
            }

            // 检查发货单状态是否可以核销
            if ($outbound->status != 2) { // 2表示待收货状态
                return response()->json([
                    'code' => 0,
                    'message' => '该发货单状态不允许核销',
                    'data' => []
                ]);
            }

            // 更新发货单状态为已完成
            $updateResult = DB::table('ims_yz_order_outbound')
                ->where('id', $outboundId)
                ->update([
                    'status' => 3, // 3表示完成状态
                    'finish_time' => time(),
                    'updated_at' => time()
                ]);

            if ($updateResult) {
                // 检查订单是否所有发货单都已完成
                $remainingOutbounds = DB::table('ims_yz_order_outbound')
                    ->where('order_id', $outbound->order_id)
                    ->where('status', '!=', 3)
                    ->count();

                // 如果所有发货单都已完成，更新订单状态
                if ($remainingOutbounds == 0) {
                    DB::table('ims_yz_order')
                        ->where('id', $outbound->order_id)
                        ->update([
                            'status' => 3, // 3表示完成状态
                            'finish_time' => time(),
                            'updated_at' => time()
                        ]);
                }

                return response()->json([
                    'code' => 1,
                    'message' => '核销成功',
                    'data' => []
                ]);
            } else {
                return response()->json([
                    'code' => 0,
                    'message' => '核销失败',
                    'data' => []
                ]);
            }

        } catch (\Exception $e) {
            Log::error('确认核销失败', [
                'error' => $e->getMessage(),
                'trace' => $e->getTraceAsString(),
                'request_data' => $request->all()
            ]);

            return response()->json([
                'code' => 0,
                'message' => '核销失败: ' . $e->getMessage(),
                'data' => []
            ]);
        }
    }

    /**
     * 获取员工授权列表
     * POST /api/verification/staff-list
     * 
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function staffList(Request $request)
    {
        try {
            // 获取参数
            $param = $request->input('param', []);
            $storeId = $param['store_id'] ?? $request->input('store_id');
            
            if (!$storeId) {
                return response()->json([
                    'code' => 0,
                    'message' => '请提供门店ID',
                    'data' => []
                ]);
            }

            // 查询已授权的员工列表
            $staffList = StaffAuth::with(['member'])
                ->byStore($storeId)
                ->authorized()
                ->notDeleted()
                ->orderBy('created_at', 'desc')
                ->get();

            // 组装返回数据
            $data = [];
            foreach ($staffList as $staff) {
                $member = $staff->member;
                $data[] = [
                    'id' => $staff->id,
                    'uid' => $staff->uid,
                    'store_id' => $staff->store_id,
                    'status' => $staff->status,
                    'status_text' => $staff->status_text,
                    'created_at' => $staff->created_at,
                    'member_info' => [
                        'uid' => $member->uid ?? 0,
                        'name' => $member->realname ?? $member->nickname ?? '未知用户',
                        'avatar' => $member->avatar ?? '/static/images/default-avatar.png',
                        'mobile' => $member->mobile ?? ''
                    ]
                ];
            }

            return response()->json([
                'code' => 1,
                'message' => '查询成功',
                'data' => $data
            ]);

        } catch (\Exception $e) {
            Log::error('查询员工授权列表失败', [
                'error' => $e->getMessage(),
                'trace' => $e->getTraceAsString(),
                'request_data' => $request->all()
            ]);

            return response()->json([
                'code' => 0,
                'message' => '查询失败: ' . $e->getMessage(),
                'data' => []
            ]);
        }
    }

    /**
     * 新增员工授权
     * POST /api/verification/staff-add
     * 
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function staffAdd(Request $request)
    {
        try {
            // 获取参数
            $param = $request->input('param', []);
            $uid = $param['uid'] ?? $request->input('uid');
            $storeId = $param['store_id'] ?? $request->input('store_id');
            $userId = $param['user_id'] ?? $request->input('user_id');
            
            if (!$uid || !$storeId || !$userId) {
                return response()->json([
                    'code' => 0,
                    'message' => '请提供完整参数：uid, store_id, user_id',
                    'data' => []
                ]);
            }

            // ✅ 应用层检查：该 uid 是否已在其他门店被授权
            $otherStoreAuth = StaffAuth::where('uid', $uid)
                ->where('store_id', '!=', $storeId)
                ->where('status', StaffAuth::STATUS_AUTHORIZED)
                ->notDeleted()
                ->first();

            if ($otherStoreAuth) {
                // 查询已授权的门店信息
                $otherStore = Store::find($otherStoreAuth->store_id);
                $otherStoreName = $otherStore ? $otherStore->store_name : '门店ID:' . $otherStoreAuth->store_id;
                
                return response()->json([
                    'code' => 0,
                    'message' => "该员工已在「{$otherStoreName}」被授权，一个员工只能被授权到一个门店",
                    'data' => [
                        'existing_store_id' => $otherStoreAuth->store_id,
                        'existing_store_name' => $otherStoreName
                    ]
                ]);
            }

            // 检查是否已存在取消授权的记录
            $existingRecord = StaffAuth::where('uid', $uid)
                ->where('store_id', $storeId)
                ->where('status', StaffAuth::STATUS_CANCELLED)
                ->notDeleted()
                ->first();

            if ($existingRecord) {
                // 更新状态为已授权
                $existingRecord->update([
                    'status' => StaffAuth::STATUS_AUTHORIZED,
                    'operate_id' => $userId,
                    'updated_at' => time()
                ]);

                return response()->json([
                    'code' => 1,
                    'message' => '授权成功（恢复授权）',
                    'data' => []
                ]);
            } else {
                // 检查是否已存在已授权的记录（当前门店）
                $authorizedRecord = StaffAuth::where('uid', $uid)
                    ->where('store_id', $storeId)
                    ->where('status', StaffAuth::STATUS_AUTHORIZED)
                    ->notDeleted()
                    ->first();

                if ($authorizedRecord) {
                    return response()->json([
                        'code' => 0,
                        'message' => '该员工已在当前门店授权',
                        'data' => []
                    ]);
                }

                // 新增授权记录
                StaffAuth::create([
                    'uid' => $uid,
                    'store_id' => $storeId,
                    'status' => StaffAuth::STATUS_AUTHORIZED,
                    'operate_id' => $userId,
                    'created_at' => time(),
                    'updated_at' => time()
                ]);

                return response()->json([
                    'code' => 1,
                    'message' => '授权成功',
                    'data' => []
                ]);
            }

        } catch (\Exception $e) {
            Log::error('新增员工授权失败', [
                'error' => $e->getMessage(),
                'trace' => $e->getTraceAsString(),
                'request_data' => $request->all()
            ]);

            return response()->json([
                'code' => 0,
                'message' => '授权失败: ' . $e->getMessage(),
                'data' => []
            ]);
        }
    }

    /**
     * 取消员工授权
     * POST /api/verification/staff-cancel
     * 
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function staffCancel(Request $request)
    {
        try {
            // 获取参数
            $param = $request->input('param', []);
            $uid = $param['uid'] ?? $request->input('uid');
            $storeId = $param['store_id'] ?? $request->input('store_id');
            $userId = $param['user_id'] ?? $request->input('user_id');
            
            if (!$uid || !$storeId || !$userId) {
                return response()->json([
                    'code' => 0,
                    'message' => '请提供完整参数：uid, store_id, user_id',
                    'data' => []
                ]);
            }

            // 查找已授权的记录
            $staffAuth = StaffAuth::where('uid', $uid)
                ->where('store_id', $storeId)
                ->where('status', StaffAuth::STATUS_AUTHORIZED)
                ->notDeleted()
                ->first();

            if (!$staffAuth) {
                return response()->json([
                    'code' => 0,
                    'message' => '未找到该员工的授权记录',
                    'data' => []
                ]);
            }

            // 更新状态为取消授权
            $staffAuth->update([
                'status' => StaffAuth::STATUS_CANCELLED,
                'operate_id' => $userId,
                'updated_at' => time()
            ]);

            return response()->json([
                'code' => 1,
                'message' => '取消授权成功',
                'data' => []
            ]);

        } catch (\Exception $e) {
            Log::error('取消员工授权失败', [
                'error' => $e->getMessage(),
                'trace' => $e->getTraceAsString(),
                'request_data' => $request->all()
            ]);

            return response()->json([
                'code' => 0,
                'message' => '取消授权失败: ' . $e->getMessage(),
                'data' => []
            ]);
        }
    }

    /**
     * 删除员工授权记录
     * POST /api/verification/staff-delete
     * 
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function staffDelete(Request $request)
    {
        try {
            // 获取参数
            $param = $request->input('param', []);
            $id = $param['id'] ?? $request->input('id');
            
            if (!$id) {
                return response()->json([
                    'code' => 0,
                    'message' => '请提供记录ID',
                    'data' => []
                ]);
            }

            // 查找记录
            $staffAuth = StaffAuth::where('id', $id)->notDeleted()->first();

            if (!$staffAuth) {
                return response()->json([
                    'code' => 0,
                    'message' => '记录不存在',
                    'data' => []
                ]);
            }

            // 软删除
            $staffAuth->update([
                'deleted_at' => time(),
                'updated_at' => time()
            ]);

            return response()->json([
                'code' => 1,
                'message' => '删除成功',
                'data' => []
            ]);

        } catch (\Exception $e) {
            Log::error('删除员工授权记录失败', [
                'error' => $e->getMessage(),
                'trace' => $e->getTraceAsString(),
                'request_data' => $request->all()
            ]);

            return response()->json([
                'code' => 0,
                'message' => '删除失败: ' . $e->getMessage(),
                'data' => []
            ]);
        }
    }

    /**
     * 通过UID查询员工信息
     * POST /api/verification/staff-info
     * 
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function staffInfo(Request $request)
    {
        try {
            // 获取参数
            $param = $request->input('param', []);
            $uid = $param['uid'] ?? $request->input('uid');
            
            if (!$uid) {
                return response()->json([
                    'code' => 0,
                    'message' => '请提供用户ID',
                    'data' => []
                ]);
            }

            // 查询会员信息
            $member = DB::table('ims_mc_members')
                ->where('uid', $uid)
                ->first();

            if (!$member) {
                return response()->json([
                    'code' => 0,
                    'message' => '用户不存在',
                    'data' => []
                ]);
            }

            // 组装返回数据
            $data = [
                'uid' => $member->uid,
                'name' => $member->realname ?: $member->nickname ?: '未知用户',
                'avatar' => $member->avatar ?: '/static/images/default-avatar.png',
                'mobile' => $member->mobile ?: '',
                'email' => $member->email ?: '',
                'realname' => $member->realname ?: '',
                'nickname' => $member->nickname ?: ''
            ];

            return response()->json([
                'code' => 1,
                'message' => '查询成功',
                'data' => $data
            ]);

        } catch (\Exception $e) {
            Log::error('查询员工信息失败', [
                'error' => $e->getMessage(),
                'trace' => $e->getTraceAsString(),
                'request_data' => $request->all()
            ]);

            return response()->json([
                'code' => 0,
                'message' => '查询失败: ' . $e->getMessage(),
                'data' => []
            ]);
        }
    }

    /**
     * 获取核销记录列表
     * POST /api/verification/verification-records
     * 
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function verificationRecords(Request $request)
    {
        try {
            // 获取参数
            $param = $request->input('param', []);
            $uid = $param['uid'] ?? $request->input('uid');
            $storeId = $param['store_id'] ?? $request->input('store_id');
            $page = $param['page'] ?? $request->input('page', 1);
            $pageSize = $param['page_size'] ?? $request->input('page_size', 10);
            
            // 必须至少提供 uid 或 store_id 中的一个
            if (!$uid && !$storeId) {
                return response()->json([
                    'code' => 0,
                    'message' => '请提供用户ID或门店ID',
                    'data' => []
                ]);
            }

            // ✅ 新逻辑：如果传uid，先查询该uid对应的store_id
            if ($uid && !$storeId) {
                // 方式1：先尝试通过 ims_hhm_staff_auth 查询（员工被授权的门店）
                $staffAuth = StaffAuth::where('uid', $uid)
                    ->where('status', StaffAuth::STATUS_AUTHORIZED)
                    ->notDeleted()
                    ->first();
                
                if ($staffAuth) {
                    // 该用户是员工，查询其被授权的门店
                    $storeId = $staffAuth->store_id;
                } else {
                    // 方式2：查询用户拥有的门店（门店主）
                    $store = Store::where('uid', $uid)->first();
                    if (!$store) {
                        return response()->json([
                            'code' => 0,
                            'message' => '该用户没有门店或未被授权',
                            'data' => []
                        ]);
                    }
                    $storeId = $store->id;
                }
            }
            
            // 此时 $storeId 一定有值了
            if (!$storeId) {
                return response()->json([
                    'code' => 0,
                    'message' => '无法获取门店信息',
                    'data' => []
                ]);
            }

            // 单独查询用户信息
            $userInfo = [
                'uid' => 0,
                'name' => '未知用户',
                'avatar' => '/static/images/default-avatar.png',
                'mobile' => ''
            ];
            
            if ($uid) {
                // 如果提供了uid，直接查询用户信息
                $user = Member::where('uid', $uid)->first();
                if ($user) {
                    $userInfo = [
                        'uid' => $user->uid,
                        'name' => $user->realname ?? $user->nickname ?? '未知用户',
                        'avatar' => $user->avatar ?? '/static/images/default-avatar.png',
                        'mobile' => $user->mobile ?? ''
                    ];
                }
            } else {
                // 如果没有提供uid，先查询门店信息获取门店的uid，再查询用户信息
                $store = Store::where('id', $storeId)->first();
                if ($store && $store->uid) {
                    $user = Member::where('uid', $store->uid)->first();
                    if ($user) {
                        $userInfo = [
                            'uid' => $user->uid,
                            'name' => $user->realname ?? $user->nickname ?? '未知用户',
                            'avatar' => $user->avatar ?? '/static/images/default-avatar.png',
                            'mobile' => $user->mobile ?? ''
                        ];
                    }
                }
            }

            // 单独查询门店信息
            $store = Store::where('id', $storeId)->first();
            $storeInfo = [
                'id' => $store->id ?? 0,
                'name' => $store->store_name ?? '未知门店',
                'address' => $store->address ?? '',
                'mobile' => $store->mobile ?? ''
            ];

            // 分别查询 type=1 和 type=2 的核销记录总数
            $type1Count = VendorVerifiy::where('store_id', $storeId)->where('type', 1);
            $type2Count = VendorVerifiy::where('store_id', $storeId)->where('type', 2);
            
            if ($uid) {
                $type1Count->where('user_id', $uid);
                $type2Count->where('user_id', $uid);
            }
            
            $type1Total = $type1Count->count();
            $type2Total = $type2Count->count();
            $totalCount = $type1Total + $type2Total;
            
            // ==================== Type 1: 置换码核销记录 ====================
            $type1Query = VendorVerifiy::with([
                'outbound.order.member',
                'outbound.outboundGoods.orderGoods.goods'
            ])
            ->where('store_id', $storeId)
            ->where('type', 1);
            
            if ($uid) {
                $type1Query->where('user_id', $uid);
            }
            
            $type1Records = $type1Query->orderBy('created_at', 'desc')
                ->offset(($page - 1) * $pageSize)
                ->limit($pageSize)
                ->get();

            // 组装 type=1 数据
            $type1RecordsList = [];
            foreach ($type1Records as $record) {
                $outbound = $record->outbound;
                $order = $outbound ? $outbound->order : null;
                $member = $order ? $order->member : null;

                // 组装商品列表
                $goodsList = [];
                if ($outbound && $outbound->outboundGoods) {
                    foreach ($outbound->outboundGoods as $outboundGood) {
                        $orderGoods = $outboundGood->orderGoods;
                        $goods = $orderGoods ? $orderGoods->goods : null;
                        
                        if ($goods) {
                            $goodsList[] = [
                                'id' => $goods->id,
                                'name' => $goods->title,
                                'quantity' => $orderGoods->total,
                                'image' => ImageUrlService::processImageUrl($goods->thumb ?: '/static/images/default-product.png'),
                                'price' => $orderGoods->price,
                                'total' => $orderGoods->price * $orderGoods->total
                            ];
                        }
                    }
                }

                $totalAmount = array_sum(array_column($goodsList, 'total'));

                $type1RecordsList[] = [
                    'id' => $record->id,
                    'outbound_id' => $record->outbound_id,
                    'user_id' => $record->user_id,
                    'vendor_id' => $record->vendor_id,
                    'store_id' => $record->store_id,
                    'created_at' => $record->created_at,
                    'type' => 1,
                    'member_info' => [
                        'uid' => $member->uid ?? 0,
                        'name' => $member->realname ?? $member->nickname ?? '未知用户',
                        'avatar' => $member->avatar ?? '/static/images/default-avatar.png',
                        'mobile' => $member->mobile ?? ''
                    ],
                    'goods_list' => $goodsList,
                    'total_amount' => $totalAmount,
                    'outbound_info' => [
                        'id' => $outbound->id ?? 0,
                        'outbound_sn' => $outbound->outbound_sn ?? '',
                        'order_sn' => $outbound->order_sn ?? '',
                        'status' => $outbound->status ?? 0,
                        'status_text' => $this->getStatusText($outbound->status ?? 0),
                        'created_at' => $outbound->created_at ?? null,
                        'send_time' => $outbound->send_time ?? null,
                        'finish_time' => $outbound->finish_time ?? null
                    ]
                ];
            }

            // ==================== Type 2: 订单核销记录（关联 ims_hhm_order）====================
            $type2Query = VendorVerifiy::where('store_id', $storeId)
                ->where('type', 2);
            
            if ($uid) {
                $type2Query->where('user_id', $uid);
            }
            
            $type2Records = $type2Query->orderBy('created_at', 'desc')
                ->offset(($page - 1) * $pageSize)
                ->limit($pageSize)
                ->get();

            // 组装 type=2 数据
            $type2RecordsList = [];
            foreach ($type2Records as $record) {
                // outbound_id 直接对应 ims_hhm_order.id
                $order = HhmOrder::find($record->outbound_id);
                
                if (!$order) {
                    continue;  // 如果订单不存在，跳过
                }
                
                // 查询订单商品
                $orderGoods = HhmOrderGoods::where('order_id', $order->id)->get();
                
                // 查询购买用户
                $member = Member::where('uid', $order->uid)->first();
                
                // 组装商品列表
                $goodsList = [];
                foreach ($orderGoods as $orderGood) {
                    $goodsList[] = [
                        'id' => $orderGood->goods_id,
                        'name' => $orderGood->title,
                        'quantity' => $orderGood->total,
                        'image' => ImageUrlService::processImageUrl($orderGood->thumb ?: '/static/images/default-product.png'),
                        'price' => $orderGood->price,
                        'total' => $orderGood->price * $orderGood->total
                    ];
                }
                
                $totalAmount = array_sum(array_column($goodsList, 'total'));

                $type2RecordsList[] = [
                    'id' => $record->id,
                    'outbound_id' => $record->outbound_id,
                    'user_id' => $record->user_id,
                    'vendor_id' => $record->vendor_id,
                    'store_id' => $record->store_id,
                    'created_at' => $record->created_at,
                    'type' => 2,
                    'member_info' => [
                        'uid' => $member->uid ?? 0,
                        'name' => $member->realname ?? $member->nickname ?? '未知用户',
                        'avatar' => $member->avatar ?? '/static/images/default-avatar.png',
                        'mobile' => $member->mobile ?? ''
                    ],
                    'goods_list' => $goodsList,
                    'total_amount' => $totalAmount,
                    'order_info' => [
                        'id' => $order->id,
                        'order_sn' => $order->order_sn,
                        'status' => $order->status,
                        'status_text' => $order->status_name ?? '',
                        'price' => $order->price,
                        'created_at' => $order->created_at,
                        'pay_time' => $order->pay_time,
                        'finish_time' => $order->finish_time
                    ]
                ];
            }

            return response()->json([
                'code' => 1,
                'message' => '查询成功',
                'data' => [
                    'user_info' => $userInfo,
                    'store_info' => $storeInfo,
                    'type1_records' => $type1RecordsList,  // 置换码核销记录
                    'type2_records' => $type2RecordsList,  // 订单核销记录
                    'pagination' => [
                        'current_page' => (int)$page,
                        'page_size' => (int)$pageSize,
                        'type1_count' => $type1Total,
                        'type2_count' => $type2Total,
                        'total_count' => $totalCount,
                        'total_pages' => ceil($totalCount / $pageSize),
                        'has_more' => $page * $pageSize < $totalCount
                    ]
                ]
            ]);

        } catch (\Exception $e) {
            Log::error('查询核销记录失败', [
                'error' => $e->getMessage(),
                'trace' => $e->getTraceAsString(),
                'request_data' => $request->all()
            ]);

            return response()->json([
                'code' => 0,
                'message' => '查询失败: ' . $e->getMessage(),
                'data' => []
            ]);
        }
    }

    /**
     * 获取门店收款码（置换码）
     * POST /api/verification/get-collection-code
     * 
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getCollectionCode(Request $request)
    {
        try {
            Log::info('[收款码生成] ========== 开始生成收款码 ==========');
            
            // 获取参数
            $param = $request->input('param', []);
            $storeId = $param['store_id'] ?? $request->input('store_id');
            $type = $param['type'] ?? $request->input('type', 1); // 默认为1（公众号）
            
            Log::info('[收款码生成] 接收参数', [
                'store_id' => $storeId,
                'type' => $type,
                'all_params' => $request->all()
            ]);
            
            if (!$storeId) {
                Log::warning('[收款码生成] 缺少门店ID');
                return response()->json([
                    'result' => 0,
                    'msg' => '请提供门店ID',
                    'data' => null
                ]);
            }
            
            // 查询门店信息
            Log::info('[收款码生成] 开始查询门店信息', ['store_id' => $storeId]);
            $store = Store::select(['uid', 'boss_uid', 'store_name', 'id'])
                ->where('id', $storeId)
                ->first();
            
            if (!$store) {
                Log::warning('[收款码生成] 门店不存在', ['store_id' => $storeId]);
                return response()->json([
                    'result' => 0,
                    'msg' => '未找到所属门店',
                    'data' => null
                ]);
            }
            
            Log::info('[收款码生成] 门店信息查询成功', [
                'store_id' => $store->id,
                'store_name' => $store->store_name,
                'uid' => $store->uid,
                'boss_uid' => $store->boss_uid
            ]);
            
            // 获取门店所有者ID
            $uid = $store->boss_uid ?: $store->uid;
            Log::info('[收款码生成] 使用门店所有者ID', ['uid' => $uid]);
            
            // 查询或创建收款码记录
            Log::info('[收款码生成] 查询收款码记录', ['store_id' => $storeId, 'type' => $type]);
            $code = CollectionCode::getStoreCode($storeId, $type);
            if (!$code) {
                Log::info('[收款码生成] 收款码记录不存在，创建新记录');
                $code = new CollectionCode();
            } else {
                Log::info('[收款码生成] 找到已有收款码记录', ['code_id' => $code->id]);
            }
            
            // 生成二维码URL
            if ($type == 1) {
                // 公众号二维码
                $url = url('https://admin.91hhm.cn/h5/pages/cashier/pay?store_id=' . $storeId . '&mid=' . $uid);
                Log::info('[收款码生成] 生成公众号二维码URL', ['url' => $url]);
                
                $qr = $this->generateQrCodeUrl($url, 'app/public/qr/cashier');
                Log::info('[收款码生成] 二维码生成成功', ['qr_url' => $qr]);
            } else {
                // 小程序二维码
                $qr = url('storage/qr/mini/' . $storeId . '_' . $uid . '.png');
                Log::info('[收款码生成] 使用小程序二维码', ['qr_url' => $qr]);
            }
            
            // 准备数据
            $setData = [
                'is_open_code' => true,
                'ico_one_url' => '',
                'ico_two_url' => '',
                'ico_three_url' => '',
                'ico_one_text' => '',
                'ico_two_text' => '',
                'ico_three_text' => '',
                'type' => $type,
                'qr_link' => $qr,
                'store_id' => $storeId,
                'custom_text' => $store->store_name
            ];
            
            Log::info('[收款码生成] 准备生成合成图片', ['set_data' => $setData]);
            
            // 生成收款码图片
            $collectionCodeLink = (new CollectionCodeService())->createCollectionCode($setData);
            
            Log::info('[收款码生成] 合成图片生成成功', ['collection_code_link' => $collectionCodeLink]);
            
            // 保存到数据库
            $data = [
                'qr_link' => $qr,
                'collection_code_link' => $collectionCodeLink,
                'store_id' => $storeId,
                'uniacid' => 1,
                'icon_link_one' => $setData['ico_one_url'],
                'icon_link_two' => $setData['ico_two_url'],
                'icon_link_three' => $setData['ico_three_url'],
                'custom_text' => $setData['custom_text'],
                'type' => $type,
                'ico_one_text' => $setData['ico_one_text'],
                'ico_two_text' => $setData['ico_two_text'],
                'ico_three_text' => $setData['ico_three_text'],
            ];
            
            Log::info('[收款码生成] 准备保存到数据库', ['data' => $data]);
            
            $code->fill($data);
            $code->save();
            
            Log::info('[收款码生成] 保存成功', ['code_id' => $code->id ?? 'new']);
            Log::info('[收款码生成] ========== 生成完成 ==========', ['final_url' => $collectionCodeLink]);
            
            return response()->json([
                'result' => 1,
                'msg' => '生成二维码成功',
                'data' => $collectionCodeLink
            ]);
            
        } catch (\Exception $e) {
            Log::error('[收款码生成] 生成失败', [
                'error' => $e->getMessage(),
                'trace' => $e->getTraceAsString(),
                'request_data' => $request->all()
            ]);
            
            return response()->json([
                'result' => 0,
                'msg' => '生成失败: ' . $e->getMessage(),
                'data' => null
            ]);
        }
    }
    
    /**
     * 生成二维码URL
     * 
     * @param string $url
     * @param string $patch
     * @return string
     */
    private function generateQrCodeUrl($url, $patch)
    {
        Log::info('[二维码生成] 开始生成二维码', ['url' => $url, 'patch' => $patch]);
        
        $fileName = md5($url);
        Log::info('[二维码生成] 文件名', ['file_name' => $fileName]);
        
        // 确保目录存在
        $dirPath = storage_path($patch);
        if (!is_dir($dirPath)) {
            Log::info('[二维码生成] 目录不存在，创建目录', ['dir' => $dirPath]);
            mkdir($dirPath, 0755, true);
        } else {
            Log::info('[二维码生成] 目录已存在', ['dir' => $dirPath]);
        }
        
        $filePath = storage_path($patch . "/{$fileName}.png");
        Log::info('[二维码生成] 目标文件路径', ['file_path' => $filePath]);
        
        // 如果文件不存在或需要重新生成
        if (file_exists($filePath)) {
            Log::info('[二维码生成] 删除旧文件');
            @unlink($filePath);
        }
        
        // 生成二维码
        Log::info('[二维码生成] 开始调用 QrCode 生成器');
        
        try {
            (new \SimpleSoftwareIO\QrCode\BaconQrCodeGenerator())
                ->format('png')
                ->size(300)
                ->generate($url, $filePath);
            
            Log::info('[二维码生成] QrCode 生成器调用完成');
        } catch (\Exception $qrException) {
            Log::error('[二维码生成] QrCode 生成器调用失败', [
                'error' => $qrException->getMessage()
            ]);
            throw $qrException;
        }
        
        if (!file_exists($filePath)) {
            Log::error('[二维码生成] 文件生成失败', ['file_path' => $filePath]);
            throw new \Exception('生成二维码失败');
        }
        
        Log::info('[二维码生成] 二维码文件生成成功', ['file_path' => $filePath]);
        
        // 返回访问URL
        $relativePath = str_replace(storage_path('app/public/'), '', $filePath);
        $fullUrl = url('storage/' . $relativePath);
        
        Log::info('[二维码生成] 生成完成', [
            'relative_path' => $relativePath,
            'full_url' => $fullUrl
        ]);
        
        return $fullUrl;
    }

    /**
     * 获取状态文本
     * 
     * @param int $status
     * @return string
     */
    private function getStatusText($status)
    {
        $statusMap = [
            -1 => '已关闭',
            0 => '未支付',
            1 => '待发货',
            2 => '待收货',
            3 => '已完成'
        ];

        return $statusMap[$status] ?? '未知状态';
    }
}
